﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using UniversalApproach.Expands;

namespace UniversalApproach.Converters
{
    /// <summary>
    /// <see cref="MD5"/>转换器
    /// </summary>
    public static class Md5Convert
    {
        /// <summary>
        /// 生成32位长MD5字符串
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <param name="capital">是否返回大写字符串<see cref="true"/>大写</param>
        /// <param name="encoder">编码类型</param>
        /// <param name="salt">盐</param>
        /// <returns></returns>
        public static string EnMd532Str(string str, bool capital = false, EncoderType encoder = EncoderType.Utf8, string salt = "")
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;

            using (var md5 = MD5.Create())
            {
                var encoderName = encoder.ToStr();

                var e = Encoding.GetEncoding(encoderName);
                if (!string.IsNullOrEmpty(salt))
                    str = salt + str;
                var r = md5.ComputeHash(e.GetBytes(str));
                var c = BitConverter.ToString(r);

                if (capital)
                    c = c.ToUpper();

                return c.Replace("-", "");
            }
        }

        /// <summary>
        /// 生成16位长MD5字符串
        /// </summary>
        /// <param name="str">要加密的字符串</param>
        /// <param name="capital">是否返回大写字符串<see cref="true"/>大写</param>
        /// <param name="encoder">编码类型</param>
        /// <param name="salt">盐</param>
        /// <returns></returns>
        public static string EnMd516Str(string str, bool capital = false, EncoderType encoder = EncoderType.Utf8, string salt = "")
        {
            var r = EnMd532Str(str, capital, encoder, salt);
            if (!string.IsNullOrEmpty(r))
                r = r.Substring(0, 16);

            return r;
        }
    }
}
